//Tooltip
function showTooltip(x, y, contents) {
    $('<div id="tooltip">' + contents + '</div>').css({
        position: 'absolute',
        display: 'none',
        top: y + 5,
        left: x + 15,
        border: '1px solid #333',
        padding: '4px',
        color: '#fff',
        'border-radius': '3px',
        'background-color': '#333',
        opacity: 0.80
    }).appendTo("body").fadeIn(200);
}



function onShowTooltip(event, pos, item) {
    $("#x").text(pos.x.toFixed(2));
    $("#y").text(pos.y.toFixed(2));

    if (item) {
        if (previousPoint != item.dataIndex) {
            previousPoint = item.dataIndex;

            $("#tooltip").remove();
            var x = item.datapoint[0].toFixed(2),
            y = item.datapoint[1].toFixed(2);

            showTooltip(item.pageX, item.pageY, item.series.label + " of " + x + " = " + y);
        }
    } else {
        $("#tooltip").remove();
        previousPoint = null;
    }
}



function start_monitor_cpu(chart_id, container_name) {
    var options = {
        series: {
            shadowSize: 1
        },
        lines: {
            show: true,
            lineWidth: 0.5,
            fill: true,
            fillColor: {
                colors: [{
                    opacity: 0.1
                }, {
                    opacity: 1
                }]
            }
        },
        yaxis: {
            min: 0,
            max: 100,
            tickFormatter: function (v) {
                return v + "%";
            }
        },
        xaxis: {
            show: false
        },
        colors: ["#e14e3d"],
        grid: {
            tickColor: "#a8a3a3",
            borderWidth: 0
        }
    };

    // Initilize the chart
    var data = [];
    var time_slice = 120;
    for (var i = 0; i < time_slice; ++i) {
        data.push([i, 0]);
    }

    var plot = $.plot($(chart_id), [data], options);

    // dynamical update data in chart
    var stats_url = '/docker/container/detail/' + container_name + "/cpu";
    var updateInterval = 1000;

    function update() {
        $.ajax({
            url: stats_url,
            type: "GET",
            dataType: "json",
            success: function (fetched_data) {
                for (var i = 1; i < time_slice; ++i) {
                    data[i-1][1] = data[i][1];
                }
                data[time_slice-1][1] = fetched_data["cpu"];
                plot.setData([data]);
                plot.draw();
            }
        });
        setTimeout(update, updateInterval);
    }
    update();

}



function start_monitor_memory(chart_id, container_name) {
    var options = {
        series: {
            shadowSize: 1
        },
        lines: {
            show: true,
            lineWidth: 0.5,
            fill: true,
            fillColor: {
                colors: [{
                    opacity: 0.1
                }, {
                    opacity: 1
                }]
            }
        },
        yaxis: {
            min: 0,
            max: 100,
            tickFormatter: function (v) {
                return v + "%";
            }
        },
        xaxis: {
            show: false
        },
        colors: ["#6ef146"],
        grid: {
            tickColor: "#a8a3a3",
            borderWidth: 0
        }
    };

    // Initilize the chart
    var data = [];
    var time_slice = 120;
    for (var i = 0; i < time_slice; ++i) {
        data.push([i, 0]);
    }

    var plot = $.plot($(chart_id), [data], options);

    // dynamical update data in chart
    var stats_url = '/docker/container/detail/' + container_name + "/memory";
    var updateInterval = 1000;

    function update() {
        $.ajax({
            url: stats_url,
            type: "GET",
            dataType: "json",
            success: function (fetched_data) {
                for (var i = 1; i < time_slice; ++i) {
                    data[i-1][1] = data[i][1];
                }
                data[time_slice-1][1] = fetched_data["memory"];
                plot.setData([data]);
                plot.draw();
            }
        });
        setTimeout(update, updateInterval);
    }
    update();

}



function start_monitor_io(chart_id, container_name) {
    var options = {
        series: {
            lines: {
                show: true,
                lineWidth: 2,
                fill: true,
                fillColor: {
                    colors: [{
                        opacity: 0.05
                    }, {
                        opacity: 0.01
                    }]
                }
            },
            points: {
                show: true
            },
            shadowSize: 2
        },
        grid: {
            hoverable: true,
            clickable: true,
            tickColor: "#eee",
            borderWidth: 0
        },
        legend: {
            position: "nw",
        },
        colors: ["#d12610", "#37b7f3", "#52e136"],
        xaxis: {
            show: false
        },
        yaxis: {
            min: 0,
            ticks: 11,
            tickDecimals: 0,
            tickFormatter: function (v) {
                return v + " MB";
            }
        }
    }

    // Initilize the chart
    var time_slice = 30;
    var data_read = [];
    var data_write = [];
    for (var i = 0; i < time_slice; ++i) {
        data_read.push([i, -1]);
        data_write.push([i, -1]);
    }
    data_read[time_slice-1][1] = 0;
    data_write[time_slice-1][1] = 0;

    var $io_chart = $(chart_id)
    $.plot($io_chart, [{
        data: data_read,
        label: "I/O Read"
    }, {
        data: data_write,
        label: "I/O Write"
    }], options);

    var previousPoint = null;
    $(chart_id).bind("plothover", onShowTooltip);

    // dynamical update data in chart
    var stats_url = '/docker/container/detail/' + container_name + "/io";
    var updateInterval = 10000;

    function update() {
        $.ajax({
            url: stats_url,
            type: "GET",
            dataType: "json",
            success: function (fetched_data) {
                for (var i = 1; i < time_slice; ++i) {
                    data_read[i-1][1] = data_read[i][1];
                    data_write[i-1][1] = data_write[i][1];
                }
                data_read[time_slice-1][1] = fetched_data["io"]["read"];
                data_write[time_slice-1][1] = fetched_data["io"]["write"];
                $.plot($io_chart, [{
                    data: data_read,
                    label: "I/O Read"
                }, {
                    data: data_write,
                    label: "I/O Write"
                }], options);
            }
        });
        setTimeout(update, updateInterval);
    }
    update();
}



function start_monitor_network(chart_id, container_name) {
    var options = {
        series: {
            lines: {
                show: true,
                lineWidth: 2,
                fill: true,
                fillColor: {
                    colors: [{
                        opacity: 0.05
                    }, {
                        opacity: 0.01
                    }]
                }
            },
            points: {
                show: true
            },
            shadowSize: 2
        },
        grid: {
            hoverable: true,
            clickable: true,
            tickColor: "#eee",
            borderWidth: 0
        },
        legend: {
            position: "nw",
        },
        colors: ["#d12610", "#37b7f3", "#52e136"],
        xaxis: {
            show: false
        },
        yaxis: {
            min: 0,
            ticks: 11,
            tickDecimals: 0,
            tickFormatter: function (v) {
                return v + " MB";
            }
        }
    }

    // Initilize the chart
    var time_slice = 30;
    var data_send = [];
    var data_recieve = [];
    for (var i = 0; i < time_slice; ++i) {
        data_send.push([i, -1]);
        data_recieve.push([i, -1]);
    }
    data_send[time_slice-1][1] = 0;
    data_recieve[time_slice-1][1] = 0;

    $network_chart = $(chart_id);
    $.plot($network_chart, [{
        data: data_send,
        label: "Inbound Traffic"
    }, {
        data: data_recieve,
        label: "Outbound Traffic"
    }], options);

    var previousPoint = null;
    $(chart_id).bind("plothover", onShowTooltip);

    // dynamical update data in chart
    var stats_url = '/docker/container/detail/' + container_name + "/network";
    var updateInterval = 10000;

    function update() {
        $.ajax({
            url: stats_url,
            type: "GET",
            dataType: "json",
            success: function (fetched_data) {
                for (var i = 1; i < time_slice; ++i) {
                    data_send[i-1][1] = data_send[i][1];
                    data_recieve[i-1][1] = data_recieve[i][1];
                }
                data_send[time_slice-1][1] = fetched_data["network"]["send"];
                data_recieve[time_slice-1][1] = fetched_data["network"]["receive"];
                $.plot($network_chart, [{
                    data: data_send,
                    label: "Inbound Traffic"
                }, {
                    data: data_recieve,
                    label: "Outbound Traffic"
                }], options);
            }
        });
        setTimeout(update, updateInterval);
    }
    update();
}



function handle_charts(container_name) {
    if (!jQuery.plot) {
        return;
    }

    start_monitor_cpu("#cpu_chart", container_name);
    start_monitor_memory("#memory_chart", container_name);
    start_monitor_io("#disk_io_chart", container_name);
    start_monitor_network("#network_traffic_chart", container_name);
}



$(document).ready(function() {
    var container_name = $("#content").html();
    handle_charts(container_name);
});